<?php

class Admin_LoginController extends Zend_Controller_Action{
    private $_isSignIn;
    public function init(){
        parent::init();
        $this->view->isSignedIn = false;
    }
    public function indexAction(){
        $this->_helper->layout->setLayout('admin');
        $this->view->form = new Admin_Form_Login();
        $filter1 = new Zend_Filter_StripTags();
        $filter2 = new Zend_Filter_StringTrim();
        $r = $this->getRequest()->getParam('redirect',null);
        if (!$this->getRequest()->isPost()) {
            $r = null!=$r?"?redirect=".$filter1->filter($filter2->filter($r)):"";
            $this->view->form->setAction('/admin/login/'.$r);
            return;
        }
		$params = $this->getRequest()->getParams();
        if ($this->view->form->isValid($params)){
			$params = $this->view->form->getValidValues($params);
			$authAdapter = new Zend_Auth_Adapter_DbTable();
            $d = new Admin_Model_DbTable_Users();
			$authAdapter->setTableName($d->info(Zend_Db_Table_Abstract::NAME))
                ->setIdentityColumn('Login')
                ->setCredentialColumn('Password')
                ->setCredentialTreatment("MD5(?)")
                ->setIdentity($params['login'])
                ->setCredential($params['password']);
            $result = $authAdapter->authenticate();
            if ($result->isValid()){
                $auth = Zend_Auth::getInstance();
                $store = $auth->getStorage();
                $data = array();
                if (!$store->isEmpty()) {
                    $data = $store->read();
                    if (!is_array($data))
                        $data = array($data);
                }
                $data['user'] = $authAdapter->getResultRowObject(null, 'Password');
				$store->write($data);
                $this->view->isSignedIn = true;
                if (null!=$r) $this->getResponse()->setRedirect($filter1->filter($filter2->filter($r)));
			}
		}
    }
    public function logoutAction(){
        $auth = Zend_Auth::getInstance();
        $auth->clearIdentity();
        exit;
    }
}